<template>
  <div>
    <el-dialog
      width="1024px"
      :close-on-click-modal="false"
      :show-close="true"
      v-bind="$attrs"
      v-on="$listeners"
      @open="onOpen"
      @close="onClose"
    >
      <div slot="title">
        {{ formData.id != null ? '修改合同' : '新增合同' }}
      </div>
      <div class="sketch_content">
        <el-form label-position="top" ref="elForm" :model="formData" :rules="rules" label-width="80px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合同编号" prop="contractSn">
                <el-input v-model="formData.contractSn" style="width: 100%"
                          placeholder="支持手动输入，为空则根据规则自动生成"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同名称" prop="contractName">
                <el-input v-model="formData.contractName" style="width: 100%"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="客户名称" prop="customerName">
                <el-input @click.native="customerIdClick" placeholder="请选择客户" v-model="formData.customerName"
                          style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商机名称" prop="businessName">
                <el-input v-model="formData.businessName" placeholder="请选择一个客户下的商机" style="width: 100%"
                          ref="businessNameRef" :disabled="formData.customerId == null" @click.native="businessIdClick"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合同金额" prop="money">
                <el-input v-model="formData.money" style="width: 100%" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="下单时间" prop="orderDate">
                <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="formData.orderDate" type="datetime"
                                placeholder="请选择" style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合同开始时间" prop="startTime">
                <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="formData.startTime" type="datetime"
                                placeholder="请选择" style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同结束时间" prop="endTime">
                <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="formData.endTime" type="datetime"
                                placeholder="请选择" style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="客户签约人" prop="contactsName">
                <el-input v-model="formData.contactsName" :disabled="formData.customerId == null"
                          @click.native="contactsIdClick"
                          style="width: 100%" placeholder="请选择一个客户下的联系人"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="公司签约人" prop="companyUserName">
                <el-input v-model="formData.companyUserName" style="width: 100%"
                          placeholder="选择公司签约人"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合同类型" prop="types">
                <el-select v-model="formData.types" placeholder="请选择" style="width: 100%">
                  <el-option
                    v-for="dict in dict.type.crm_contract_category"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input
                  type="textarea"
                  :autosize="{ minRows: 3, maxRows: 5}"
                  placeholder="请输入内容"
                  v-model="formData.remark"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <dialog-add-product ref="dialogAddProduct" @callback="productSelectCallback"></dialog-add-product>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="submitForm" :loading="submitLoading">保 存</el-button>
        <el-button size="small" @click="onClose">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 客户选择 -->
    <customer-select-popover ref="customerSelectPopover" @callback="customerDataCallback"
                             v-if="customerPopoverVisiable"
    />
    <!-- 商机选择 -->
    <business-select-popover ref="businessSelectPopover" @callback="businessDataCallback"
                             v-if="businessPopoverVisiable"
    />
    <!-- 联系人选择 -->
    <contacts-select-popover ref="contactsSelectPopover" @callback="contactsDataCallback"
                             v-if="contactsPopoverVisiable"
    />
  </div>
</template>

<script>
import { listProductFromBusiness } from '@/api/crm/Business'
import {
  listProductByContract,
  saveHasKey,
  selectByPrimaryKey,
  updateByPrimaryKeySelective
} from '@/api/crm/Contract'

import CustomerSelectPopover from '@/components/Crm/Customer/CustomerSelectPopover'
import BusinessSelectPopover from '@/components/Crm/Business/BusinessSelectPopover'
import ContactsSelectPopover from '@/components/Crm/Contacts/ContactsSelectPopover'
import DialogAddProduct from '@/components/Crm/Product/DialogAddProduct'

export default {
  inheritAttrs: false,
  name: 'ContractDialog',
  dicts: ['crm_contract_category'],
  components: {
    CustomerSelectPopover,
    BusinessSelectPopover,
    ContactsSelectPopover,
    DialogAddProduct
  },
  props: {
    pk: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      dialogVisible: false,
      customerPopoverVisiable: false,
      businessPopoverVisiable: false,
      contactsPopoverVisiable: false,
      submitLoading: false,
      formData: {
        id: null, // 主键id
        contractSn: '', // 合同编号
        contractName: '', // 合同名称,
        customerName: '', // 客户名称
        customerId: null, // 客户id
        businessName: '', // 商机名称
        businessId: null, // 商机id
        money: null, // 合同金额
        orderDate: null, // 下单时间
        startTime: null, // 合同开始时间
        endTime: null, // 合同结束时间
        contactsName: '', // 客户签约人姓名
        contactsId: null, // 客户签约人id
        companyUserName: '', // 公司签约人姓名
        companyUserId: null, // 公司签约人id
        types: null, // 合同类型
        remark: '', // 备注
        discountRate: null, // 整单折扣
        totalPrice: null, // 产品总金额
        productList: [] // 产品列表
      },
      totalMoney: 0,
      key: 0,
      rules: {
        contractName: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }],
        customerName: [{ required: true, message: '请选择客户', trigger: 'change' }],
        money: [{ required: true, message: '请输入合同金额', trigger: 'blur' }],
        orderDate: [{ required: true, message: '请选择下单时间', trigger: 'blur' }]
      },
      queryParams: {
        page: 1,
        limit: 15,
        search: '',
        searchId: null
      }
    }
  },
  // 在实例创建完成后被立即调用
  created() {
    this.submitLoading = false
  },
  // 实例被挂在后调用
  mounted() {

  },
  // 方法
  methods: {
    // 对话框打开
    async onOpen() {
      if (this.pk != null) {
        await selectByPrimaryKey(this.pk).then(res => {
          this.formData = res.data
        })
        this.queryParams.searchId = this.formData.id
        listProductByContract(this.queryParams).then(res => {
          this.formData.productList = res.data.records
          this.$refs.dialogAddProduct.initProductData(this.formData)
        })
      }
    },
    // 对话框关闭
    onClose() {
      this.dialogVisible = false
      this.customerPopoverVisiable = false
      this.businessPopoverVisiable = false
      this.submitLoading = false
      this.$refs['elForm'].resetFields()
      this.$emit('update:visible', false)
    },
    // 提交
    submitForm() {
      // this.submitLoading = true
      this.$refs['elForm'].validate(valid => {
        if (valid) {
          if (this.formData.id != undefined) {
            // 修改
            updateByPrimaryKeySelective(this.formData).then(res => {
              this.$modal.msgSuccess('修改成功')
              this.$emit('ok')
              this.onClose()
            })
          } else {
            // 新增
            saveHasKey(this.formData).then(res => {
              this.$modal.msgSuccess('新增成功')
              this.$emit('ok')
              this.onClose()
            })
          }
        }
      })
    },
    // 客户input点击事件
    customerIdClick() {
      this.customerPopoverVisiable = true
      this.$nextTick(() => {
        this.$refs.customerSelectPopover.open()
      })
    },
    // 客户弹出框回调
    customerDataCallback(data) {
      // 如果旧id不等于新id，则证明客户变更了，需要重置商机和客户签约人
      if (this.formData.customerId != data.id) {
        this.formData.businessId = null
        this.formData.businessName = ''
        this.formData.contactsId = null
        this.formData.contactsName = ''
      }
      this.formData.customerId = data.id
      this.formData.customerName = data.customerName
    },
    // 商机input点击事件
    businessIdClick() {
      if (this.formData.customerId != null) {
        this.businessPopoverVisiable = true
        this.$nextTick(() => {
          this.$refs.businessSelectPopover.open(this.formData.customerId, 2)
        })
      }
    },
    // 商机弹出框回调
    businessDataCallback(data) {
      this.formData.businessId = data.id
      this.formData.businessName = data.businessName
      // 查询该商机关联的产品信息
      this.queryParams.searchId = this.formData.businessId
      listProductFromBusiness(this.queryParams).then(res => {
        this.formData.productList = res.data.records
        this.$refs.dialogAddProduct.initProductData(this.formData)
      })
    },
    // 联系人input点击事件
    contactsIdClick() {
      if (this.formData.customerId != null) {
        this.contactsPopoverVisiable = true
        this.$nextTick(() => {
          this.$refs.contactsSelectPopover.open(this.formData.contactsId, 3)
        })
      }
    },
    // 联系人弹出框回调
    contactsDataCallback(data) {
      this.formData.contactsId = data.id
      this.formData.contactsName = data.name
    },
    // 产品列表信息变化回调
    productSelectCallback({ discountRate, money, productList }) {
      this.formData.discountRate = discountRate
      this.formData.money = money
      this.formData.productList = productList
      this.formData.totalPrice = money
    }
  }
}
</script>

<style scoped>
</style>
